package cn.kooki.app.duobao.ui.Activity.Pay;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.base.BaseNavActivity;
import cn.kooki.app.duobao.core.MainFactory;
import cn.kooki.app.duobao.data.Bean.User.UserInfo;
import cn.kooki.app.duobao.data.Bean.User.pay.PayCallBackItem;
import cn.kooki.app.duobao.data.Bean.User.pay.PayCallBackResponse;
import cn.kooki.app.duobao.data.Bean.base.BaseResponse;
import cn.kooki.app.duobao.data.bus.ChangePageEvent;
import cn.kooki.app.duobao.data.constant.Constants;
import cn.kooki.app.duobao.ui.Activity.Comm.RootAcitivity;
import cn.kooki.app.duobao.ui.Activity.User.ChangeRecordActivity;
import cn.kooki.app.duobao.ui.Activity.User.DuobaoRecordActivity;
import cn.kooki.app.duobao.ui.Fragment.duobaorecord.DuobaoRecordItemFragment;
import cn.kooki.app.duobao.ui.widget.CustomRelativeLayout;
import cn.kooki.app.duobao.ui.widget.PushWinDialogUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.ShareUtils;
import cn.kooki.app.duobao.util.manager.AppManager;
import cn.kooki.app.duobao.util.manager.LoginManager;
import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by xiong on 2016/1/3.
 */
public class PayCallBackActivity extends BaseNavActivity implements View.OnClickListener {
    @Bind(R.id.pay_result_title)
    TextView payResultTitle;
    @Bind(R.id.btn_warpper)
    LinearLayout btnWarpper;
    @Bind(R.id.shop_number)
    LinearLayout shopNumber;
    @Bind(R.id.shop_list)
    ListView shopList;
    @Bind(R.id.root)
    LinearLayout root;

    public static final int ORDER_TYPE = 1;
    public static final int CHARGE_TYPE = 2;
    @Bind(R.id.btn_left)
    Button btnLeft;
    @Bind(R.id.btn_right)
    Button btnRight;
    @Bind(R.id.loadingWrapper)
    CustomRelativeLayout loadingWrapper;
    @Bind(R.id.result_wrapper)
    RelativeLayout resultWrapper;
    @Bind(R.id.pay_resulting_code)
    TextView payResultingCode;
    @Bind(R.id.pay_resulting_title)
    TextView payResultingTitle;
    @Bind(R.id.btn_refresh)
    Button btnRefresh;
    @Bind(R.id.resulting_wrapper)
    RelativeLayout resultingWrapper;
    @Bind(R.id.tv_shop_num)
    TextView tvShopNum;
    @Bind(R.id.tv_shop_money)
    TextView tvShopMoney;
    @Bind(R.id.btn_post_bonus)
    Button btnPostBonus;
    @Bind(R.id.tv_post_bonus)
    TextView tvPostBonus;
    @Bind(R.id.layout_post_bonus)
    LinearLayout layoutPostBonus;
    private int type;

    private PayCallBackResponse callbackdata;
    private PayCallBackAdapter payCallBackAdapter;
    private UserInfo userinfo;
    private String code;
    private String paycode;
    private String url;
    private String content;

    @Override
    public void setLayoutContainerView() {
        setContainerView(R.layout.activity_pay_result);
        ButterKnife.bind(this);
    }

    @Override
    protected void afterView() {
        type = getIntent().getIntExtra("type", CHARGE_TYPE);
        code = getIntent().getStringExtra("code");
        paycode = getIntent().getStringExtra("pay_code");
        userinfo = SharePreferencesUtils.getUserinfo(this);
        root.setVisibility(View.GONE);
        btnLeft.setOnClickListener(this);
        btnRight.setOnClickListener(this);
        btnRefresh.setOnClickListener(this);
        setTitle(R.string.title_activity_pay_result);
        if (type == CHARGE_TYPE) {
            btnLeft.setText("返回首页");
            btnRight.setText("查看充值记录");
        } else if (type == ORDER_TYPE) {
            btnLeft.setText("继续夺宝");

            btnRight.setText("点击查看夺宝记录");
        }
        loadingWrapper.showloading();
        getresult();
        payCallBackAdapter = new PayCallBackAdapter();
        shopList.setAdapter(payCallBackAdapter);
        btnPostBonus.setOnClickListener(this);

    }

    private void getresult() {
        HashMap<String, Object> dingdan = new HashMap<>();
        if (!TextUtils.isEmpty(paycode)) {
            dingdan.put("dingdan", paycode);
        } else {
            dingdan.put("dingdan", code);
        }
        MainFactory.getApiInstance().paycallback(userinfo.getUid(), dingdan, type, new Callback<PayCallBackResponse>() {
            @Override
            public void success(PayCallBackResponse baseResponse, Response response) {
                if (baseResponse.getStatus() == 0) {
                    callbackdata = baseResponse;
                    refresh(true);
                } else {
                    refresh(false);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                refresh(false);
            }
        });
    }


    private void getIsOne() {
        MainFactory.getApiInstance().IsOneBonus(userinfo.getUid(), 2, new Callback<BaseResponse>() {
            @Override
            public void success(BaseResponse baseResponse, Response response) {
                if (baseResponse.getStatus() == 0) {
                    PushWinDialogUtils.showFristDilaog(PayCallBackActivity.this, true);
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }

    private ArrayList<PayCallBackItem> goodlist = new ArrayList<>();

    private void refresh(boolean isresult) {
        root.setVisibility(View.VISIBLE);
        resultingWrapper.setVisibility(isresult ? View.GONE : View.VISIBLE);
        resultWrapper.setVisibility(isresult ? View.VISIBLE : View.GONE);
        loadingWrapper.hideloading();
        String dingdan = "";
        if (!TextUtils.isEmpty(paycode)) {
            dingdan = paycode;
        } else {
            dingdan = code;
        }
        layoutPostBonus.setVisibility(View.GONE);
        if (isresult) {
            if (callbackdata != null) {
                LoginManager.checkIsNew(userinfo.getUid());
                layoutPostBonus.setVisibility(View.VISIBLE);
                if (type == CHARGE_TYPE) {
                    String paytitle = getResources().getString(R.string.pay_callback_title);
                    paytitle = String.format(paytitle, callbackdata.money);
                    payResultTitle.setText(paytitle);
                    shopNumber.setVisibility(View.GONE);
                    shopList.setVisibility(View.GONE);
                } else if (type == ORDER_TYPE) {
                    String paytitle = getResources().getString(R.string.pay_callback_title);
                    goodlist.clear();
                    goodlist.addAll(callbackdata.data);
                    tvShopNum.setText(callbackdata.shopnum + "");
                    tvShopMoney.setText(callbackdata.num + "");
                    shopNumber.setVisibility(View.VISIBLE);
                    shopList.setVisibility(View.VISIBLE);
                    payCallBackAdapter.notifyDataSetChanged();
                }
                getIsOne();
            } else {

                SpannableString string = new SpannableString("订单号:" + dingdan);
                string.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red)), 4, dingdan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                payResultingCode.setText(string);
            }
        } else {
            SpannableString string = new SpannableString("订单号:" + dingdan);
            string.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.red)), 4, dingdan.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            payResultingCode.setText(string);
        }
    }

    class PayCallBackAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return goodlist.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            PayCallBackItem item = goodlist.get(position);
            if (convertView == null) {
                convertView = LayoutInflater.from(PayCallBackActivity.this).inflate(R.layout.layout_list_good, parent, false);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.tvShopGoodname.setText(item.title);
            SpannableString numstring = new SpannableString(item.num + "人次");
            numstring.setSpan(new ForegroundColorSpan(PayCallBackActivity.this.getResources().getColor(R.color.red)), 0, item.num.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            viewHolder.tvShopNum.setText(numstring);
            viewHolder.tvShopResultCode.setText("夺宝号码:" + item.code);
            viewHolder.tvShopResultQishu.setText("商品期号:" + item.qishu);
            return convertView;
        }

        /**
         * This class contains all butterknife-injected Views & Layouts from layout file 'layout_list_good.xml'
         * for easy to all layout elements.
         *
         * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers (http://github.com/avast)
         */
        class ViewHolder {
            @Bind(R.id.tv_shop_goodname)
            TextView tvShopGoodname;
            @Bind(R.id.tv_shop_num)
            TextView tvShopNum;
            @Bind(R.id.tv_shop_result_qishu)
            TextView tvShopResultQishu;
            @Bind(R.id.tv_shop_result_code)
            TextView tvShopResultCode;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }


    @Override
    public void onClick(View v) {
        if (v == btnLeft) {
            ChangePageEvent pageEvent = new ChangePageEvent();
            EventBus.getDefault().post(pageEvent);
            AppManager.getAppManager().getTopWith(RootAcitivity.class);
        }
        if (v == btnRight) {
            if (type == CHARGE_TYPE) {
                AppManager.getAppManager().finishActivity(ChangeRecordActivity.class);
                intent(ChangeRecordActivity.class);
                finish();
            } else if (type == ORDER_TYPE) {
                intent(DuobaoRecordActivity.class, "type", DuobaoRecordItemFragment.CURRT_TYPE);
                finish();
            }
        }
        if (v == btnRefresh) {
            loadingWrapper.showloading();
            getresult();
        }
        if (v == btnPostBonus) {
            postBonus();
        }
    }

    private void postBonus() {
        new AlertDialog.Builder(this)
                .setView(R.layout.layout_share_bonus)
                .setNegativeButton("分享红包给好友", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showShareDialog();
                    }
                }).setPositiveButton("取消", null).show();
    }


    private void showShareDialog() {
        content = "一元收获惊喜，亲测有效！现在我把好运气人品都传给你，快来领取吧！";
        final String title = "朋友夺到宝，分给你了！";
        final UMImage image = new UMImage(this, R.drawable.takeout_ic_coupon_wm);
        ShareUtils shareUtils = new ShareUtils();
        UserInfo userinfo = SharePreferencesUtils.getUserinfo(this);
        url = Constants.APP_SHARE_URL + userinfo.getUid();
        final String finalTitle = title;
        shareUtils.showShareDialog(this, new ShareUtils.shareItemClickLister() {
            @Override
            public void onClick(SHARE_MEDIA media) {
                if (media == SHARE_MEDIA.SINA) {
                    content = content + url;
                }
                new ShareAction(PayCallBackActivity.this)
                        .setPlatform(media)
                        .setCallback(umShareListener).withTitle(finalTitle).withMedia(image)
                        .withText(content).withTargetUrl(url)
                        .share();
            }
        });
    }


    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA share_media) {
            showToastMessage("分享成功");
        }

        @Override
        public void onError(SHARE_MEDIA share_media, Throwable throwable) {
            showToastMessage("分享失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media) {
            showToastMessage("分享取消");
        }
    };

}
